package com.kit.data.kitopeso.analysis.libs

import android.app.Application
import androidx.fragment.app.FragmentActivity
import com.google.android.play.core.review.ReviewInfo
import com.google.android.play.core.review.ReviewManager
import com.google.android.play.core.review.ReviewManagerFactory

object RateLib {

    @Volatile
    private var _rm: ReviewManager? = null

    @Volatile
    private var _rd: ReviewInfo? = null

    fun fetch(context: Application) {
        _rm = ReviewManagerFactory.create(context)
        _rm?.requestReviewFlow()?.addOnCompleteListener { task ->
            if (task.isSuccessful) {
                _rd = task.result
            } else {
                println("Review request failed: ${task.exception?.message}")
            }
        }
    }

    fun launchFlow(activity: FragmentActivity, completed: (Boolean) -> Unit) {
        val reviewInfo = _rd
        if (reviewInfo == null) {
            completed(false)
            return
        }

        val reviewManager = _rm
        if (reviewManager == null) {
            completed(false)
            return
        }

        reviewManager.launchReviewFlow(activity, reviewInfo).addOnCompleteListener {
            completed(true)
        }
    }
}